package com.itheima.health.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.PermissionDao;
import com.itheima.health.dao.RolePermissionDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.RolePermission;
import com.itheima.health.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
@Slf4j
@DubboService
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private RolePermissionDao rolePermissionDao;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page pages = permissionDao.findPage(queryPageBean.getQueryString());
        PageResult pageResult = new PageResult();
        pageResult.setRows(pages.getResult());
        pageResult.setTotal(pages.getTotal());
        return pageResult;
    }

    @Override
    public List all() {
        List<Permission> permissions = permissionDao.selectAll();
        return permissions;
    }

    @Override
    public int add(Permission permission, Integer[] roles) {
        int i = permissionDao.insertSelective(permission);
        Permission byName = permissionDao.findByName(permission.getName());
        for (Integer role : roles) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setPermissionId(byName.getId());
            rolePermission.setRoleId(role);
            rolePermissionDao.insertSelective(rolePermission);
        }
        return i;
    }

    @Override
    public List findByPermissionRoleId(Integer id) {
        List list = rolePermissionDao.findByPermissionRoleId(id);
        return list;
    }

    @Override
    public Permission findById(Integer id) {
        Permission byId1 = permissionDao.findById1(id);
        return byId1;
    }

    @Override
    public int edit(Permission permission, Integer[] roles) {
        int i = permissionDao.updateByPrimaryKeySelective(permission);
        rolePermissionDao.deleteById(permission.getId());
        for (Integer integer : roles) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setPermissionId(permission.getId());
            rolePermission.setRoleId(integer);
            rolePermissionDao.insertSelective(rolePermission);
        }
        return i;
    }

    @Override
    public int deleteById(Integer id) {
        rolePermissionDao.deleteById(id);
        int i = permissionDao.deleteById(id);
        return i;
    }
}
